package com.deep.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deep.common.model.constant.CartConstant;
import com.deep.common.model.dto.MemberResponseVO;
import com.deep.common.model.dto.OrderDTO;
import com.deep.common.model.dto.SkuHasStockTO;
import com.deep.common.model.dto.mq.SeckillOrderDTO;
import com.deep.common.utils.PageUtils;
import com.deep.common.utils.Query;
import com.deep.common.utils.R;
import com.deep.order.dao.OrderDao;
import com.deep.order.exception.NoStockException;
import com.deep.order.feign.CartFeignService;
import com.deep.order.feign.MemberFeignService;
import com.deep.order.feign.ProductFeignService;
import com.deep.order.feign.WareFeignService;
import com.deep.order.interceptor.LoginInterceptor;
import com.deep.order.model.constant.OrderConstant;
import com.deep.order.model.constant.PayConstant;
import com.deep.order.model.dto.OrderCreateDTO;
import com.deep.order.model.dto.SpuInfoDTO;
import com.deep.order.model.dto.WareSkuLockDTO;
import com.deep.order.model.entity.OrderEntity;
import com.deep.order.model.entity.OrderItemEntity;
import com.deep.common.model.enume.OrderStatusEnum;
import com.deep.order.model.entity.PaymentInfoEntity;
import com.deep.order.model.vo.*;
import com.deep.order.model.vo.pay.PayAsyncVO;
import com.deep.order.model.vo.pay.PayVO;
import com.deep.order.service.FareService;
import com.deep.order.service.OrderItemService;
import com.deep.order.service.OrderService;
import com.deep.order.service.PaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVO> orderSubmitVOThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private FareService fareService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        // 1、获取当前用户登录的信息
        MemberResponseVO memberResponseVO = LoginInterceptor.loginUser.get();
        // ①获取当前请求属性（解决异步编排时请求头共享问题）
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        // 2、获取用户收货地址
        CompletableFuture<Void> setAddressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(attributes);
            List<MemberAddressVO> addressVOS = memberFeignService.getAddress(memberResponseVO.getId());
            orderConfirmVO.setMemberAddressVos(addressVOS);
        }, executor);

        // 3、获取商品项
        CompletableFuture<Void> setCartItemsFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVO> currentCartItems = cartFeignService.getCurrentCartItems();
            orderConfirmVO.setItems(currentCartItems);
        }, executor).thenRunAsync(() -> {
            // 3.1设置库存
            List<Long> skuIds = orderConfirmVO.getItems().stream().map(OrderItemVO::getSkuId).collect(Collectors.toList());
            // 查询远程库存系统
            List<SkuHasStockTO> hasStockTOList = wareFeignService.getSkusHasStock(skuIds);
            if (hasStockTOList != null && hasStockTOList.size() > 0) {
                Map<Long, Boolean> map = hasStockTOList.stream().collect(Collectors.toMap(SkuHasStockTO::getSkuId, SkuHasStockTO::getHasStock));
                orderConfirmVO.setStocks(map);
            }
        }, executor);

        // 4、查询用户积分
        Integer integration = memberResponseVO.getIntegration();
        orderConfirmVO.setIntegration(integration == null ? 0 : integration);

        // TODO 5、防重令牌(防止表单重复提交)
        // 为用户设置一个token，三十分钟过期时间（存在redis）
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVO.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVO.setOrderToken(token);

        CompletableFuture.allOf(setAddressFuture, setCartItemsFuture).get();
        return orderConfirmVO;
    }

    // @Transactional(isolation = Isolation.READ_COMMITTED) 设置事务的隔离级别
    // @Transactional(propagation = Propagation.REQUIRED)   设置事务的传播级别
    // @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional
    @Override
    public SubmitOrderResponseVO submitOrder(OrderSubmitVO orderSubmitVO) {
        Assert.notNull(orderSubmitVO, "orderSubmitVO!");
        // 前端传来的token
        String orderToken = orderSubmitVO.getOrderToken();
        if (orderToken != null) {
            // 获取当前登录用户token
            MemberResponseVO memberResponseVO = LoginInterceptor.loginUser.get();
            String redisTokenKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVO.getId();
            // 验证并删除token(原子操作)
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Collections.singletonList(redisTokenKey), orderToken);
            if (result != null && result == 1L) {
                // 验证成功
                orderSubmitVOThreadLocal.set(orderSubmitVO);    // 将orderSubmitVO放在本地线程中共享
                // 1、创建订单
                OrderCreateDTO order = createOrder();
                // 2、验证价格
                BigDecimal payAmount = order.getOrder().getPayAmount(); // 订单生成的价格
                BigDecimal payPrice = orderSubmitVO.getPayPrice();  // 前端传来的价格
                return compareAmount(order, payAmount, payPrice);
            }
        }
        SubmitOrderResponseVO submitOrderResponseVO = new SubmitOrderResponseVO();
        submitOrderResponseVO.setCode(0);
        return submitOrderResponseVO;
//        throw new IllegalArgumentException("orderToken为空!");
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        Assert.notNull(orderSn, "orderSn不能为空!");
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        // 关闭订单之前先查询一下数据库，判断此订单状态是否已支付
        OrderEntity orderInfo = this.getOne(new QueryWrapper<OrderEntity>().
                eq("order_sn", orderEntity.getOrderSn()));

        if (orderInfo.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            // 代付款状态进行关单
            orderInfo.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderInfo);

            // 发送消息给MQ
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderInfo, orderDTO);
            try {
                //TODO 确保每个消息发送成功，给每个消息做好日志记录，(给数据库保存每一个详细信息)保存每个消息的详细信息
                //TODO 定期扫描数据库，重新发送失败的消息

                // 防止服务器卡顿造成解锁失败
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderDTO);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public PayVO getOrderPay(String orderSn) {
        Assert.notNull(orderSn, "orderSn不能为空!");

        PayVO payVO = new PayVO();
        // 获取当前订单信息
        OrderEntity orderInfo = this.getOrderByOrderSn(orderSn);
        // 保留两位小数点，向上取值
        BigDecimal payAmount = orderInfo.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVO.setTotal_amount(payAmount.toString());
        payVO.setOut_trade_no(orderInfo.getOrderSn());

        // 查询订单项的数据
        List<OrderItemEntity> orderItemEntities = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemEntities.get(0);
        payVO.setSubject(orderItemEntity.getSkuName());
        payVO.setBody(orderItemEntity.getSkuAttrsVals());

        return payVO;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVO memberResponseVO = LoginInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id", memberResponseVO.getId()).orderByDesc("create_time")
        );

        // 遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            // 根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(orderItemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntityList);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVO payAsyncVO) {
        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(payAsyncVO.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(payAsyncVO.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(payAsyncVO.getBuyer_pay_amount()));
        paymentInfo.setSubject(payAsyncVO.getBody());
        paymentInfo.setPaymentStatus(payAsyncVO.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(payAsyncVO.getNotify_time());
        //添加到数据库中
        paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = payAsyncVO.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = payAsyncVO.getOut_trade_no(); //获取订单号
            updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderDTO orderDTO) {
        Assert.notNull(orderDTO, "orderDTO不能为空!");
        // 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderDTO.getOrderSn());
        orderEntity.setMemberId(orderDTO.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderDTO.getSeckillPrice().multiply(BigDecimal.valueOf(orderDTO.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        this.save(orderEntity);

        // 保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderDTO.getOrderSn());
        orderItem.setRealAmount(totalPrice);
        orderItem.setSkuQuantity(orderDTO.getNum());
        R spuInfo = productFeignService.getSpuInfoBySkuId(orderDTO.getSkuId());
        SpuInfoDTO spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoDTO>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());
        orderItemService.save(orderItem);
    }

    private void updateOrderStatus(String orderSn, Integer code, Integer payType) {
        baseMapper.updateOrderStatus(orderSn, code, payType);
    }

    private SubmitOrderResponseVO compareAmount(OrderCreateDTO order, BigDecimal payAmount, BigDecimal payPrice) throws NoStockException {
        MemberResponseVO memberResponseVO = LoginInterceptor.loginUser.get();
        SubmitOrderResponseVO submitOrderResponseVO = new SubmitOrderResponseVO();
        submitOrderResponseVO.setCode(0);
        // 验证价格(前端传来的价格和生成订单的价格是否一致)
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
            // 验证通过
            // 3、保存订单
            saveOrder(order);
            // 4、库存锁定,只要有异常，回滚订单数据
            WareSkuLockDTO lockDTO = new WareSkuLockDTO();
            lockDTO.setOrderSn(order.getOrder().getOrderSn());
            List<OrderItemVO> orderItemVOS = order.getOrderItems().stream().map((item) -> {
                OrderItemVO orderItemVO = new OrderItemVO();
                orderItemVO.setSkuId(item.getSkuId());
                orderItemVO.setCount(item.getSkuQuantity());
                orderItemVO.setTitle(item.getSkuName());
                return orderItemVO;
            }).collect(Collectors.toList());
            lockDTO.setLocks(orderItemVOS);

            // 调用远程锁定库存的方法
            // 出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
            // 为了保证高并发，不推荐使用seata，因为是加锁，并行化，提升不了效率,可以发消息给库存服务
            R r = wareFeignService.orderLockStock(lockDTO);
            if (r.getCode() == 0) {
                // 锁定成功
                submitOrderResponseVO.setOrder(order.getOrder());
                //TODO 订单创建成功，发送消息给MQ
                rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                // 删除购物车里的数据
                redisTemplate.delete(CartConstant.CART_PREFIX + memberResponseVO.getId());
                return submitOrderResponseVO;
            }
            // 锁定库存失败
//            String msg = (String) r.get("data");
//            throw new NoStockException(msg);
            // 锁定库存失败
            submitOrderResponseVO.setCode(3);
            return submitOrderResponseVO;
        }
        // 订单商品价格发生变化
        submitOrderResponseVO.setCode(2);
        return submitOrderResponseVO;
    }

    /**
     * 保存订单
     *
     * @param orderCreateDTO
     */
    private void saveOrder(OrderCreateDTO orderCreateDTO) {
        Assert.notNull(orderCreateDTO, "order不能为空!");
        // 获取订单信息
        OrderEntity order = orderCreateDTO.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        // 保存订单
        this.baseMapper.insert(order);
        // 获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateDTO.getOrderItems();
        // 批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 生成订单
     */
    private OrderCreateDTO createOrder() {
        OrderCreateDTO order = new OrderCreateDTO();
        // 1、生成订单号
        String orderSn = IdWorker.getTimeId();
        // 构建订单数据【封装价格】
        OrderEntity orderEntity = builderOrder(orderSn);

        // 2、获取到所有的订单项【封装价格】
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn);

        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity, orderItemEntities);

        order.setOrder(orderEntity);
        order.setOrderItems(orderItemEntities);

        return order;
    }

    /**
     * 计算价格的方法
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        // 订单总额
        BigDecimal total = new BigDecimal("0.0");
        // 优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        // 积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;
        // 订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            // 订单总额
            total = total.add(orderItemEntity.getRealAmount());
            // 优惠价格信息
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            // 积分信息和成长值信息
            integrationTotal += orderItemEntity.getGiftIntegration();
            growthTotal += orderItemEntity.getGiftGrowth();
        }
        // 设置订单总额
        orderEntity.setTotalAmount(total);
        // 设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);
        // 设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
        // 设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建所有订单项数据
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn) {
        Assert.notNull(orderSn, "orderSn不能为空!");
        List<OrderItemEntity> orderItemEntities = new ArrayList<>();

        List<OrderItemVO> currentCartItems = cartFeignService.getCurrentCartItems();
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntities = currentCartItems.stream().map(item -> {
                // 构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntities;
    }

    /**
     * 构建订单项数据
     */
    private OrderItemEntity builderOrderItem(OrderItemVO orderItemVO) {
        Assert.notNull(orderItemVO, "orderItemVO不能为空!");
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1、商品的spu信息
        Long skuId = orderItemVO.getSkuId();
        // 调用远程getSpuInfoBySkuId方法
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoDTO spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoDTO>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());
        // 2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(orderItemVO.getTitle());
        orderItemEntity.setSkuPic(orderItemVO.getImage());
        orderItemEntity.setSkuPrice(orderItemVO.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVO.getCount());
        // 使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(orderItemVO.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);
        //TODO 3、商品的优惠信息

        // 4、商品的积分信息
        orderItemEntity.setGiftGrowth(orderItemVO.getPrice()
                .multiply(new BigDecimal(orderItemVO.getCount())).intValue());
        orderItemEntity.setGiftIntegration(orderItemVO.getPrice()
                .multiply(new BigDecimal(orderItemVO.getCount())).intValue());

        // 5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        // 当前订单项的实际金额.总额 - 各种优惠价格
        // 原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice()
                .multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        // 原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    /**
     * 构建订单数据
     */
    private OrderEntity builderOrder(String orderSn) {
        Assert.notNull(orderSn, "orderSn不能为空!");
        // 获取当前登录用户
        MemberResponseVO memberResponseVO = LoginInterceptor.loginUser.get();
        // 封装订单购基本信息(登录者信息)
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberResponseVO.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVO.getUsername());
        // 获取提交的订单
        OrderSubmitVO orderSubmitVO = orderSubmitVOThreadLocal.get();

        //远程获取收货地址和运费信息
        FareVO fareVO = fareService.getFare(orderSubmitVO.getAddrId());
        MemberAddressVO address = fareVO.getAddress();
        // 设置运费和收货人信息
        orderEntity.setFreightAmount(fareVO.getFare());
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);

        return orderEntity;
    }
}